package com.hxc.common.config;

import com.hxc.common.common.ResultCode;
import com.hxc.common.common.ResultVO;
import com.hxc.common.utils.LogHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理
 */
@RestControllerAdvice
public class ExceptionControllerAdvice {
    public static final Logger logger = LoggerFactory.getLogger(ExceptionControllerAdvice.class);

    //自定义异常信息
    @ExceptionHandler(APIException.class)
    public ResultVO<String> APIExceptionHandler(APIException e) {
        LogHelper.writeLog(e, logger);
        return new ResultVO<>(ResultCode.FAILED, e.getMsg());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResultVO<String> MethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        // 从异常对象中拿到ObjectError对象
        ObjectError objectError = e.getBindingResult().getAllErrors().get(0);
        // 然后提取错误提示信息进行返回
        LogHelper.writeLog(e, logger);
        return new ResultVO<>(ResultCode.VALIDATE_FAILED, objectError.getDefaultMessage());
    }

    @ExceptionHandler(Exception.class)
    public ResultVO<String> ExceptionHandler(Exception e) {
        LogHelper.writeLog(e, logger);
        return new ResultVO<>(ResultCode.ERROR.getCode(), e.toString());
    }
}
